package com.cityfood.controller;


import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpSession;

import com.cityfood.common.utils.JsonUtils;
import com.cityfood.common.utils.MyStringUtils;
import com.cityfood.service.*;
import com.github.pagehelper.PageInfo;

import weixin.popular.util.JsonUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cityfood.common.pojo.CityFoodResult;
import com.cityfood.common.pojo.OrderTradeStatus;
import com.cityfood.common.utils.OrderNoUtil;
import com.cityfood.pojo.CfCard;
import com.cityfood.pojo.CfCart;
import com.cityfood.pojo.CfOrder;
import com.cityfood.pojo.CfProduct;
import com.cityfood.pojo.CfProductSpecs;
import com.cityfood.pojo.CfStation;
import com.cityfood.pojo.CfUser;
import com.cityfood.pojo.CfUserAddress;

@Controller
public class OrderController {
	//注入adminUserService接口实现类
	@Autowired
	private OrderService orderService;
	
	//注入商品规格操作接口
	@Autowired
	private ProductSpecsService specsService;
	
	//注入商品操作接口
	@Autowired
	private ProductService productService;

	//注入用户地址操作接口
	@Autowired
	private AddressService addressService;
	
	// 注入高铁站操作接口
	@Autowired
	private StationService stationService;
	
	// 注入购物车操作接口
	@Autowired
	private CartService cartService;
	
    // 注入用户操作接口
    @Autowired
    private UserService userService;
    
    //注入收礼卡接口
    @Autowired
    private CardService cardService;
	
	@RequestMapping(value="/orders",method=RequestMethod.POST)
	@ResponseBody
	public CityFoodResult confirmOrder(HttpSession session,
										@RequestParam Integer userId,
										@RequestParam String consignee,
										@RequestParam String phone,
										@RequestParam String address,
										@RequestParam(defaultValue="1") Integer deliveryType,
										@RequestParam(defaultValue="1") Integer buyAim,
										@RequestParam(defaultValue="0") Integer needinvoice,
										@RequestParam(defaultValue="") String title,
										@RequestParam(defaultValue="1") Integer type,
										@RequestParam(defaultValue="") String taxnumber){
		
		CityFoodResult cfr = new CityFoodResult();
		CfOrder order = new CfOrder();
		//订单商品总数量
		int amount = 0;
		//订单商品总金额
		double money = 0;
		
		
		
		//用户id
		order.setUserId(userId);
		
		Map<String,Integer> buyCartList = (Map<String,Integer>)session.getAttribute("buyCart");
		if (buyCartList==null) {
			cfr.setCode(500);
			cfr.setData("");
			cfr.setMsg("订单生成失败");
			return cfr;
		}
		Map<String, Integer> specsMap = new  LinkedHashMap<String, Integer>();
		String orderSpecsId="0";
		for (String buyCartSpecsId : buyCartList.keySet()) {
			
			specsMap.put( buyCartSpecsId, buyCartList.get(buyCartSpecsId)); 	
			
			CfProductSpecs specs = specsService.getProductSpecsBySpecsId(Integer.parseInt(buyCartSpecsId));
			money=money+specs.getPrice().doubleValue()*buyCartList.get(buyCartSpecsId);
			amount=amount+buyCartList.get(buyCartSpecsId);
			orderSpecsId=buyCartSpecsId;
		}
		String specsJSON = JsonUtils.objectToJson(specsMap);
		//用户购买商品json字符串：Map<Integer,Integer> specsId,num
		order.setProductSpecsIds(specsJSON);
		
		//订单编号生成，使用第一个speceId
		order.setOrderno(OrderNoUtil.gens(orderSpecsId));
		
		//订单状态，默认为0，未支付
		order.setTradeStatus((byte)0);
		
		if (amount<=0) {
			cfr.setCode(500);
			cfr.setData("");
			cfr.setMsg("订单生成失败");
			return cfr;
		}
		//用户购买商品总数
		order.setProductNum(amount);
		
		if (money<=0) {
			cfr.setCode(500);
			cfr.setData("");
			cfr.setMsg("订单生成失败");
			return cfr;
		}
		
		order.setConsignee(consignee);
		order.setPhone(phone);
		order.setAddress(address);
		//订单总金额
		BigDecimal price = new BigDecimal(money);
		order.setTotalMoney(price);
		
		//订单配送方式，1.闪送；2.自提;3.物流
		order.setDeliveryType(deliveryType.byteValue());
		
		//订单购买方式，1.自购；2.送礼
		order.setBuyAim(buyAim.byteValue());
		
		boolean isNeedinvoice = false;
		if (needinvoice==1) {
			isNeedinvoice=true;
		}
		//是否需要发票
		order.setNeedinvoice(isNeedinvoice);
		
		//企业抬头
		order.setTitle(title);
		
		//1，个人；2，企业,默认是1
		order.setType(type.byteValue());
		
		//企业税号,默认为空
		order.setTaxnumber(taxnumber);
		
		//订单创建时间
		order.setCreateTime(new Date());
		
		//订单修改时间
		order.setUpdateTime(new Date());
		
		//创建订单
		int res = orderService.createOrder(order);
		
		if(res != 0){
			//订单生成成功，删除购物车结算商品
			CfCart cart = cartService.getCartByUserId(userId);
			Map<String,Integer> userCart = (Map<String, Integer>)JsonUtils.jsonToMap(cart.getCartList());
			for (String buy : specsMap.keySet()) {
				if (userCart.containsKey(buy)) {
					userCart.remove(buy);
				}
			}
			cart.setCartList(JsonUtils.objectToJson(userCart));
			int i = cartService.updateCart(cart);
			if (i <= 0) {
				cfr.setCode(201);
				cfr.setMsg("删除购物车失败");
				cfr.setData(false);
				return cfr;
			}
			// 放入session
			session.setAttribute("cart", userCart);
			
			//订单生成成功就减去库存
			for (String specsId : specsMap.keySet()) {
				int j = specsService.updateProductSpecsSubtract(Integer.parseInt(specsId), specsMap.get(specsId));
				if (j <= 0) {
					cfr.setCode(201);
					cfr.setMsg("减少库存失败");
					cfr.setData(false);
					return cfr;
				}
			}
			cfr.setCode(200);
			cfr.setData(order.getId());
			cfr.setMsg("订单生成成功");
		}else{
			cfr.setCode(500);
			cfr.setData(0);
			cfr.setMsg("订单生成失败");
		}
		return cfr;
	}
	
	@RequestMapping(value = "/orders/{id}", method = RequestMethod.GET)
	@ResponseBody
	public CityFoodResult getOrder(@PathVariable Integer id) {
		CityFoodResult cfr = new CityFoodResult();
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		CfOrder order = orderService.getOrder(id);
		CfCard  card = cardService.selectCardByOrderId(id);
		if (order != null) {

			Map<String, Object> mp = new LinkedHashMap<>();
			mp.put("orderId", order.getId());
			mp.put("cardId", card == null ? 0 : card.getId()); //0表实此订单未包含礼品卡
			mp.put("buyAim", order.getBuyAim());
			mp.put("status", order.getTradeStatus());
			mp.put("orderNo", order.getOrderno());
			mp.put("orderCreateTime", sd.format(order.getCreateTime()));
			mp.put("nowTime", sd.format(new Date()));
			mp.put("payType", "微信支付");
			mp.put("deliveryType", order.getDeliveryType());
			mp.put("totalNum", order.getProductNum());
			mp.put("totalPrice", order.getTotalMoney());
			//运费，待定
			mp.put("freight", 10);
			//配送人员: 闪送和自提情况下有返回值；物流快递情况下返回空，界面可不显示
			mp.put("deliveryWorker", 10);
			//配送人员联系方式： 使用同上
			mp.put("deliveryWorkerPhone", 10);
			//配送类型
			mp.put("deliveryTime", "立即配送");
			//接受人名称
			mp.put("reciverName", order.getConsignee());
			//接受人电话
			mp.put("reciverPhone", order.getPhone());
			//收货地址 ： 闪送为指定集结点，自提为门店地址，快递为用户收货地址
			mp.put("address", order.getAddress());
			//物流信息
			mp.put("express", 10);
			//运单号 
			mp.put("expressNo", 10);

			//订单商品明细表
			mp.put("products", this.fomatOrderItemList(order.getProductSpecsIds()));
			
			cfr.setCode(200);
			cfr.setMsg("获取订单详情成功");
			cfr.setData(mp);
		} else {
			cfr.setCode(500);
			cfr.setMsg("订单详情为空");
			cfr.setData("");
		}
		return cfr;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/orders/my",method=RequestMethod.GET)
	@ResponseBody
	public CityFoodResult getMyOrders(HttpSession session,
										@RequestParam Integer userId,
										@RequestParam(defaultValue="100") Integer status,
										@RequestParam(defaultValue="1") Integer currentPage){
		
		CityFoodResult cfr = new CityFoodResult();
		PageInfo<CfOrder> orderListPage = new PageInfo<>(null);
		
		if (status==100) {
			orderListPage = orderService.getMyOrdersAndPage(userId, currentPage);
		}else{
			orderListPage = orderService.getMyOrdersByStatusAndPage(userId, status, currentPage);
		}
		if(orderListPage!=null){
			List<Map<String,Object>> ls = new  ArrayList<>();
			
			for (CfOrder order : orderListPage.getList()) {
				Map<String,Object> mp = new LinkedHashMap<>();
				mp.put("orderId", order.getId());
				mp.put("buyAim", order.getBuyAim());
				mp.put("status", order.getTradeStatus());
				//读取订单表商品规格json数据，转为map
				Map<String,Integer> productSpecsMap = (Map<String,Integer>)JsonUtils.jsonToMap(order.getProductSpecsIds());
				//遍历查询到订单信息里面的所以规格信息
				for (String specsId : productSpecsMap.keySet()) {
					//根据规格id查询到规格信息
					CfProductSpecs specs = specsService.getProductSpecsBySpecsId(Integer.parseInt(specsId));
					//根据规格找到商品
					CfProduct cfProduct = productService.getProductByProductId(specs.getProductId());
					
					mp.put("productId", cfProduct.getId());
					mp.put("productName", cfProduct.getName());
					mp.put("productPic", cfProduct.getMainImage());
					mp.put("price", specs.getPrice());
					mp.put("num", productSpecsMap.get(specsId));
					mp.put("attrs", MyStringUtils.getSpecsStr(specs.getProductSpecs()));
					break;
				}
				mp.put("totalPrice", order.getTotalMoney());
				mp.put("totalNum", order.getProductNum());
				mp.put("freight", 10);
				ls.add(mp);
				
			}
			List<Map<String,Object>> tabs = new  ArrayList<>();
			Map<String,Object> tab = new LinkedHashMap<>();
			List<CfOrder> orderStatusList = orderService.getMyOrders(userId);
			int status0=0;
			int status1=0;
			int status2=0;
			int status6=0;
			int status8=0;
			int status5=0;  //未赠送
			for (CfOrder cfOrder : orderStatusList) {
				if (cfOrder.getTradeStatus()==0) {
					status0=status0+1;
				}else if(cfOrder.getTradeStatus()==1){
					status1=status1+1;
				}else if(cfOrder.getTradeStatus()==2){
					status2=status2+1;
				}else if(cfOrder.getTradeStatus()==6){
					status6=status6+1;
				}else if(cfOrder.getTradeStatus()==8){
					status8=status8+1;
				}else if(cfOrder.getTradeStatus()==5){
					status5=status+1; 
				}
			}
			
			//待付款、
			tab.put("0", status0);
			//进行中、
			tab.put("1",status1);
			//待评价、
			tab.put("2", status2);
			//待赠送、
			tab.put("6", status6);
			//退款
			tab.put("8", status8);
			//未赠送
			tab.put("5", status5);
			tabs.add(tab);
			Map<String,Object> ms = new LinkedHashMap<>();
			ms.put("total", orderListPage.getTotal());
			ms.put("tabs", tabs);
			ms.put("orders", ls);
			cfr.setCode(200);
			cfr.setMsg("获取订单列表成功");
			cfr.setData(ms);
		}else{
			cfr.setCode(500);
			cfr.setMsg("订单列表为空");
			cfr.setData("");
		}
		return cfr;
	}
	/**
	 * 调用微信支付接口
	 * @param orderId
	 * @return
	 */
	@RequestMapping(value="/orders/{id}/pay",method=RequestMethod.PUT)
	@ResponseBody
	public CityFoodResult orderPay(@RequestParam(value="orderId") Integer orderId){
		CityFoodResult cfr = new CityFoodResult();
		int res = orderService.orderPay(orderId);
		if(res != 0){
			cfr.setCode(200);
			cfr.setData("");
			cfr.setMsg("订单支付成功");
		}else {
            cfr.setCode(500);
            cfr.setData("");
            cfr.setMsg("订单支付失败");
        }

		return cfr;
	}
	
	/**
	 * 送礼 
	 * @param orderId
	 * @return
	 */
	@RequestMapping(value="/orders/{id}/persentpay",method=RequestMethod.PUT)
	@ResponseBody
	public CityFoodResult orderPersentPay(int orderId){
		CityFoodResult cfr = new CityFoodResult();
		int res = orderService.orderPersentPay(orderId);
		if(res != 0){
			cfr.setCode(200);
			cfr.setData("");
			cfr.setMsg("送礼支付成功");
		}else{
			cfr.setCode(500);
			cfr.setData("");
			cfr.setMsg("送礼支付失败");
		}
		return cfr;
	}
	
	/**
	 * 买家收货
	 * @param orderId
	 * @return
	 */
	@RequestMapping(value="/orders/{id}/delivery",method=RequestMethod.PUT)
	@ResponseBody
	public CityFoodResult orderDelivery(int orderId){
		CityFoodResult cfr = new CityFoodResult();
		int res = orderService.orderDelivery(orderId);
		if(res != 0){
			cfr.setCode(200);
			cfr.setData("");
			cfr.setMsg("订单收货成功");
		}else{
			cfr.setCode(500);
			cfr.setData("");
			cfr.setMsg("订单收货失败");
		}
		return cfr;
	}
	
	/**
	 * 订单取消
	 * @param orderId
	 * @return
	 */
	@RequestMapping(value="/orders/{id}/cancel",method=RequestMethod.PUT)
	@ResponseBody
	public CityFoodResult orderCancel(int orderId){
		CityFoodResult cfr = new CityFoodResult();
		int res = orderService.orderCancel(orderId);
		if(res != 0){
			cfr.setCode(200);
			cfr.setData("");
			cfr.setMsg("订单取消成功");
		}else{
			cfr.setCode(500);
			cfr.setData("");
			cfr.setMsg("订单取消失败");
		}
		return cfr;
	}
	
	/**
	 * 订单评价，废弃
	 * @param orderId
	 * @return
	 */
	@RequestMapping(value="/orders/{id}/comment",method=RequestMethod.PUT)
	@ResponseBody
	public CityFoodResult orderComment(int orderId){
		CityFoodResult cfr = new CityFoodResult();
		int res = orderService.orderComment(orderId);
		if(res != 0){
			cfr.setCode(200);
			cfr.setData("");
			cfr.setMsg("订单评论成功");
		}else{
			cfr.setCode(500);
			cfr.setData("");
			cfr.setMsg("订单评论失败");
		}
		return cfr;
	}
	
    /**
     * 按状态查询订单
     * @param userId
     * @param tradeStatus
     * @return
     */
	@RequestMapping(value="/orders?userId={userId}&tradeStatus={tradeStatus}",method=RequestMethod.GET)
	@ResponseBody
	public CityFoodResult getOrdersByStatus(@PathVariable Integer userId,@PathVariable Integer tradeStatus){
		CityFoodResult cfr = new CityFoodResult();
		List<CfOrder> list = orderService.getOrdersByStatus(userId, tradeStatus);
		if(list != null){
			if(!list.isEmpty()){
				cfr.setCode(200);
				cfr.setData(list);
				cfr.setMsg("获取列表成功");
			}else{
				cfr.setCode(201);
				cfr.setData("");
				cfr.setMsg("订单列表为空");
			}
		}else{
			cfr.setCode(500);
			cfr.setData("");
			cfr.setMsg("服务器错误");
		}
		return cfr;
	}
	
	 /**
     * 订单处理 ：4 取消订单 2收货确认 3评价订单  6送礼成功   5购买礼品成功
     * @param orderId
     * @param status
     * @return
     */
	@RequestMapping(value="/orders/changeStatus",method=RequestMethod.PUT)
	@ResponseBody
	public CityFoodResult updateOrdersStatus(@RequestParam Integer orderId,@RequestParam Integer status){
		CityFoodResult cfr = new CityFoodResult();
		CfOrder order = new CfOrder();
		order.setId(orderId);
		order.setTradeStatus(status.byteValue());
		order.setUpdateTime(new Date());
		int i = orderService.updateOrderStatus(order);
		if(i>0){
			cfr.setCode(200);
			
			if(status==OrderTradeStatus.WAIT_COMMENT.getStatus()) {
				cfr.setMsg("收货成功");

			}else if(status==OrderTradeStatus.FINISH.getStatus()){
				cfr.setMsg("评论订单成功");	
			}else if(status==OrderTradeStatus.CANCEL.getStatus()){
				cfr.setMsg("取消订单 成功");	
				CfOrder cfOrder = orderService.getOrder(orderId);
				//读取订单表商品规格json数据，转为map
				Map<String,Integer> productSpecsMap = (Map<String,Integer>)JsonUtils.jsonToMap(cfOrder.getProductSpecsIds());
				//恢复库存
				for (String specsId : productSpecsMap.keySet()) {
					int j = specsService.updateProductSpecsAdd(Integer.parseInt(specsId), productSpecsMap.get(specsId));
					if (j<=0) {
						cfr.setCode(201);
						cfr.setMsg("恢复库存失败");	
					}
				}	
			}else if(status==OrderTradeStatus.WAIT_RECEIVE.getStatus()){
				cfr.setMsg("送礼成功，待收礼");	
			}
			cfr.setData(true);
		}else{
			cfr.setCode(500);
			cfr.setData("");
			cfr.setMsg("服务器错误");
		}
		return cfr;
	}
	
	/**
	 *  获取订单配送地址列表
	 */
	@RequestMapping(value = "/orders/deliveryInfo", method = RequestMethod.GET)
	@ResponseBody
	public CityFoodResult getAddressBydelivery(@RequestParam Integer userId,
												@RequestParam Integer deliveryType,
												@RequestParam Integer cityId) {
		CityFoodResult cityFoodResult = new CityFoodResult();
		//根据用户id获取所有地址信息
		List<CfUserAddress> addressList = addressService.getAddressByUserId(userId);
		CfUser user= userService.getUserByUserId(userId);
		List<Map<String,Object>> ls = new ArrayList<>();
		if (deliveryType == 1) {
			//根据用户id获取所有地址信息
			List<CfStation> stations = stationService.getStationByCityId(cityId);
			for (CfStation address : stations) {
				
				Map<String,Object> mp = new LinkedHashMap<>();
				mp.put("consignee", user.getNickname());
				mp.put("phone", user.getPhone());
				mp.put("address", address.getName()+address.getRallyPoint());
				ls.add(mp);
			}
			

		} else if(deliveryType == 2){
			
			List<CfStation> stations = stationService.getStationByCityId(cityId);
			
			for (CfStation address : stations) {
				
				Map<String,Object> mp = new LinkedHashMap<>();
				mp.put("consignee", user.getNickname());
				mp.put("phone", user.getPhone());
				mp.put("address", address.getName() + address.getDeliverPoint());
				ls.add(mp);	
			}

		}else if(deliveryType == 3){
			
			for (CfUserAddress address : addressList) {
				
				Map<String,Object> mp = new LinkedHashMap<>();
				mp.put("consignee", address.getConsignee());
				mp.put("phone", address.getPhone());
				mp.put("province",address.getProvince());
				mp.put("city", address.getCity());
				mp.put("county", address.getCounty());
				mp.put("detailAddress", address.getDetailedAddress());
				mp.put("address", address.getProvince()+address.getCity()+address.getCounty()+
						address.getStreet()+address.getDetailedAddress());
				ls.add(mp);
				
			}
		}
		if (ls.size()>0) {
			cityFoodResult.setCode(200);
			cityFoodResult.setMsg("获取订单配送地址列表成功");
			cityFoodResult.setData(ls);
			return cityFoodResult;
		}
		cityFoodResult.setCode(201);
		cityFoodResult.setMsg("获取订单配送地址列表");
		cityFoodResult.setData("");
		return cityFoodResult;
	}

	//后台管理---------------------------------------------------------------------------


    /**
     *
     * @param condition  多条件查询json串 ： {"orderNo": 1111,"start":"2019-01-02"...}
     * @return
     * @throws Exception 
     */
    @RequestMapping(value="/manage/orders",method=RequestMethod.GET)
    @ResponseBody
	public CityFoodResult getOrders(@RequestParam(value = "conditions",defaultValue = "") String conditions,
        @RequestParam(value = "currentPage",defaultValue="1") int currentPage) throws Exception {
        CityFoodResult res = new CityFoodResult();
        
        String filter = URLDecoder.decode(conditions,"UTF-8");
        
        PageInfo<CfOrder> list = orderService.getOrderList( filter,currentPage);
        
        Map<String,Object> map = new HashMap<>();
        
        if(list != null){
        	map.put("total", list.getSize());
        	map.put("orders", this.fomatOrderList(list.getList()));
            res.setCode(200);
            res.setData(map);
            if(list.getTotal() > 0)
                res.setMsg("获取订单成功");
            else
                res.setMsg("获取订单为空");
        }else{
            res.setCode(500);
            res.setData("");
            res.setMsg("服务器错误");
        }
		return res;
	}

    /**
     * 订单中的商品详情列表格式化接口返回
     * @param specsJsonStr
     * @return
     */
	private List<Map<String,Object>> fomatOrderItemList(String specsJsonStr){
        // 读取订单表商品规格json数据，转为map
        Map<String, Integer> productSpecsMap = (Map<String, Integer>) JsonUtils.jsonToMap(specsJsonStr);
        //订单里面的商品集合
        List<Map<String, Object>> productList = new ArrayList<>();
        // 遍历查询到订单信息里面的所以规格信息
        for (String specsId : productSpecsMap.keySet()) {
            Map<String, Object> product = new LinkedHashMap<>();
            // 根据规格id查询到规格信息
            CfProductSpecs specs = specsService.getProductSpecsBySpecsId(Integer.parseInt(specsId));
            // 根据规格找到商品
            CfProduct cfProduct = productService.getProductByProductId(specs.getProductId());

            product.put("productId", cfProduct.getId());
            product.put("productName", cfProduct.getName());
            product.put("productPic", cfProduct.getMainImage());
            product.put("price", specs.getPrice());
            product.put("num", productSpecsMap.get(specsId));
            product.put("attrs", MyStringUtils.getSpecsStr(specs.getProductSpecs()));

            productList.add(product);
        }

        return productList;
    }

    /**
     * 后台订单列表格式化
     * @param orders
     * @return
     */
	private List<Map<String,Object>> fomatOrderList(List<CfOrder> orders){
        List<Map<String,Object>> list = new ArrayList<>();
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
        for(CfOrder order : orders){
            Map<String,Object> map = new HashMap<>();
            map.put("userName",userService.getUserByUserId(order.getUserId()).getNickname());
            map.put("orderNo",order.getOrderno());
            map.put("orderCreateTime",sd.format(order.getCreateTime()));
            map.put("buyAim",order.getBuyAim());
            map.put("status",order.getTradeStatus());
            map.put("deliveryType",order.getDeliveryType());
            map.put("consignee",order.getConsignee());
            map.put("phone",order.getPhone());
            map.put("address",order.getAddress());
            map.put("products",this.fomatOrderItemList(order.getProductSpecsIds()));
            map.put("prodcutNum",order.getProductNum());
            map.put("totalMoney",order.getTotalMoney());

            list.add(map);
        }

        return list;
    }


}


